const urljoin = require('url').resolve

const _ = require('lodash')
const { JSDOM } = require('jsdom')


module.exports = class Response {
    constructor(request, {
        statusCode,
        body,
        headers,
    }) {
        this.request = request
        this.statusCode = statusCode
        this.body = body
        this.headers = headers
    }

    get url() {
        return this.request.url
    }

    get dom() {
        if (_.isUndefined(this.jsdom)) {
            this.jsdom = new JSDOM(this.body, {
                url: this.url,
                referer: this.request.referer,
            })
        }
        return this.jsdom
    }

    get window() {
        return this.dom.window
    }

    get $() {
        if (_.isUndefined(this.jquery)) {
            this.jquery = require('jquery')(this.window)
        }
        return this.jquery
    }

    urljoin(path) {
        return urljoin(this.request.url, path)
    }

    follow(url, options) {
        throw new Error('follow method not implement')
    }

    serialize() {
        return JSON.stringify({
            statusCode: this.statusCode,
            body: this.body,
            headers: this.headers,
        })
    }

    static deserialize(request, s) {
        const data = JSON.parse(s)
        return new Response(request, data)
    }
}